//
//  ApartmentHotelScheduleViewController.m
//  House
//
//  Created by 张垚 on 16/7/21.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "ApartmentHotelScheduleViewController.h"
#import "BaseTitleNavigationBar.h"
#import "MoveHousePushTableViewCell.h"
#import "LabelAndTextFieldView.h"
#import "SubmitMenuManager.h"

@interface ApartmentHotelScheduleViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIButton *submitButton;

@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *placeHolderArr;

@property (nonatomic, strong) NSArray *keyArr;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ApartmentHotelScheduleViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //本地数据
    _titleArr = @[@"联系人", @"联系电话", @"入住日期", @"到店时间", @"住店天数"];
    _placeHolderArr = @[@"请输入真实姓名", @"请输入11位手机号", @"请选择入驻日期", @"请选择到店时间", @"请输入住店天数"];
    //顶部视图
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"酒店预定"];
    [self.view addSubview:_myBar];
    //返回视图添加手势 用于返回
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [_myBar.leftView addGestureRecognizer:tap];
    [self initTableView];
    [self submitView];
    //上传服务器的参数
    _keyArr = @[@"userid", @"itemid", @"username", @"tel", @"timedates", @"times", @"dates"];
    // Do any additional setup after loading the view.
}
#pragma mark - tableview部分
//初始化
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 220) style:UITableViewStylePlain];
    _tableView.tableFooterView = [UIView new];
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[MoveHousePushTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MoveHousePushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.isPush = NO;
    cell.inputView.titleLabel.text = _titleArr[indexPath.row];
    cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.row];
    cell.inputView.contextTextField.delegate = self;
    if (indexPath.row == 2 || indexPath.row == 3) {
        cell.tag = indexPath.row;
        cell.inputView.contextTextField.userInteractionEnabled = NO;
    }
    return cell;
}
//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2 || indexPath.row == 3) {
        MoveHousePushTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        if (indexPath.row == 2) {
            datePicker.datePickerMode = UIDatePickerModeDate;
        }else {
            datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        }
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//空格是为了给datePicker腾出空间显示
        [alertController.view addSubview:datePicker];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSDate *selectDate = [datePicker date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            if (indexPath.row == 2) {
                [dateFormatter setDateFormat:@"YYYY-MM-dd"];
                NSString *dateStr = [dateFormatter stringFromDate:selectDate];
                cell.inputView.contextTextField.text = dateStr;
            }else {
                [dateFormatter setDateFormat:@"MM-dd HH:mm"];
                NSString *dateStr = [dateFormatter stringFromDate:selectDate];
                cell.inputView.contextTextField.text = dateStr;
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:sureAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
#pragma mark - 提交订单
//视图
- (void)submitView {
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_submitButton];
    UIView *superView = self.view;
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tableView.mas_bottom).offset(40);
        make.left.equalTo(superView.mas_left).offset(80);
        make.right.equalTo(superView.mas_right).offset(-80);
        make.height.equalTo(@40);
    }];
    _submitButton.layer.cornerRadius = 6;
    _submitButton.layer.masksToBounds = YES;
    _submitButton.backgroundColor = [UIColor colorWithRed:212 / 255.0f green:38 / 255.0f blue:26 / 255.0f alpha:1.0];
    [_submitButton setTitle:@"提交并支付" forState:UIControlStateNormal];
    [_submitButton addTarget:self action:@selector(submitInfo:) forControlEvents:UIControlEventTouchUpInside];
}
//提交事件
- (void)submitInfo:(UIButton *)button {
   NSDictionary *submitDic = [SubmitMenuManager submitHotelTableView:_tableView WithKeyArr:_keyArr WithHotelId:_itemID];
    if ([submitDic[@"username"] isEqualToString:@""]) {
        [self alertMessage:@"请输入姓名"];
    }else if ([self valiMobile:submitDic[@"tel"]] != nil) {
        [self alertMessage:[self valiMobile:submitDic[@"tel"]]];
    }else if ([submitDic[@"timedates"] isEqualToString:@""]) {
        [self alertMessage:@"请选择入住日期"];
    }else if ([submitDic[@"times"] isEqualToString:@""]) {
        [self alertMessage:@"请选择到店时间"];
    }else if ([submitDic[@"dates"] isEqualToString:@""]) {
        [self alertMessage:@"请输入入住天数"];
    }else {
        _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _hud.label.text = @"正在提交订单";
        [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/ding" parameters:submitDic progress:^(NSProgress *progress) {
        } success:^(id response) {
            if ([response[@"flag"] isEqualToString:@"1"]) {
                _hud.label.text = @"提交成功";
                [_hud hideAnimated:YES afterDelay:1];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self back];
                });
            }else {
                _hud.label.text = @"提交失败";
                [_hud hideAnimated:YES afterDelay:1];
            }
        } failure:^(NSError *error) {
            _hud.label.text = @"服务器异常";
            [_hud hideAnimated:YES afterDelay:1];
        }];
    }
}

//判断手机号是否正确
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"请输入11位手机号";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确格式的手机号";
        }
    }
    return nil;
}

//信息不全 提示信息
- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}

//返回上一界面
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

//点击textfiled return收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
